<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-button type="primary" @click="dialogRolesVisible=true">添加角色</el-button>
      <!-- 角色列表区域 -->
      <el-table :data="roleslist" stripe border style="width: 100%">
        <el-table-column type="expand">
          <template v-slot:default='scope'>
            <el-row v-for="(item1,index1) in scope.row.children" :key="item1.id" :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']">
              <!-- 一级权限列表 -->
              <el-col :span='5'>
                <el-tag closable disable-transitions @close="removeRightsTags(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 其余权限列表 -->
              <el-col :sapn='19'>
                <el-row v-for="(item2,index2) in item1.children" :key="item2.id" :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']">
                  <!-- 二级权限列表 -->
                  <el-col :span="6">
                    <el-tag type="success" closable disable-transitions @close="removeRightsTags(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限列表 -->
                    <el-tag v-for="(item3) in item2.children" :key="item3.id" type="warning" closable disable-transitions @close="removeRightsTags(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="角色名称" prop="roleName" min-width="180px">
        </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc" min-width="180px">
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot:default='scope'>
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showModifyDialog(scope.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoles(scope.row.id)">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button type=" warning" icon="el-icon-setting" size="mini" @click="showRightsForm(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色区域 -->
      <el-dialog title="添加角色" :visible.sync="dialogRolesVisible" width="50%" @close="resetForm">
        <!-- 内容区 -->
        <el-form ref="addRolesFormRef" :model="addRolesForm" :rules="rules" label-width="80px">
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 按钮区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogRolesVisible = false">取 消</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改角色信息区域 -->
      <el-dialog title="修改角色信息" :visible.sync="dialogModifyRolesVisible" width="50%" @close="resetModifyRolesForm">
        <el-form ref="modifyRolesFormRef" :model="modifyRolesForm" :rules="rules" label-width="80px">
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="modifyRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="roleDesc">
            <el-input v-model="modifyRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogModifyRolesVisible = false">取 消</el-button>
          <el-button @click="resetModifyRolesForm">重置</el-button>
          <el-button type="primary" @click="modifyRoles">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限区域 -->
      <el-dialog title="分配权限" :visible.sync="dialogRightsVisible" width="50%">
        <!-- 树形控件 -->
        <el-tree :data="RightsForm" :props="rightsProps" show-checkbox node-key="id" default-expand-all ref="treeRef" :default-checked-keys="defaultRightsKeys"></el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogRightsVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'MyRoles',
  data() {
    return {
      roleslist: [],
      dialogRolesVisible: false,
      dialogModifyRolesVisible: false,
      dialogRightsVisible: false,
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      modifyRolesForm: {},
      RightsForm: [],
      // 树形控件的属性绑定
      rightsProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的三级权限节点的id值数组
      defaultRightsKeys: [],
      // 角色id
      roleId: 0,
      rules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色相关描述', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 渲染角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.roleslist = res.data
      // console.log(this.roleslist)
    },
    // 添加角色
    addRoles() {
      this.$refs.addRolesFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/roles', this.addRolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功')
        this.dialogRolesVisible = false
        this.getRolesList()
      })
    },
    // 重置添加角色表单
    resetForm() {
      this.$refs.addRolesFormRef.resetFields()
    },
    // 根据id查询角色信息
    async showModifyDialog(id) {
      this.dialogModifyRolesVisible = true
      const { data: res } = await this.$http.get('/roles/' + id)
      if (res.meta.status !== 200) return
      this.modifyRolesForm = res.data
      // console.log(this.modifyRolesForm)
    },
    // 重置修改角色信息表单
    resetModifyRolesForm() {
      this.$refs.modifyRolesFormRef.resetFields()
    },
    // 修改角色
    modifyRoles() {
      this.$refs.modifyRolesFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('/roles/' + this.modifyRolesForm.roleId, { roleName: this.modifyRolesForm.roleName, roleDesc: this.modifyRolesForm.roleDesc })
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色失败！')
        }
        this.$message.success('修改角色成功')
        this.dialogModifyRolesVisible = false
        this.getRolesList()
      })
    },
    // 删除角色
    removeRoles(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const { data: res } = await this.$http.delete('/roles/' + id)
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
          this.getRolesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除tag标签
    removeRightsTags(role, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const { data: res } = await this.$http.delete('/roles/' + role.id + '/rights/' + rightId)
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除权限成功!'
            })
          }
          // this.getRolesList()
          role.children = res.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 展示分配权限表单
    async showRightsForm(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('/rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      this.RightsForm = res.data
      // console.log(this.RightsForm)
      // 调用递归函数之前先清空数组
      this.defaultRightsKeys = []
      // 通过递归获取三级权限的id
      this.getKeys(role, this.defaultRightsKeys)
      this.dialogRightsVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      } else {
        node.children.forEach(item => {
          this.getKeys(item, arr)
        })
      }
    },
    // 为角色分配权限
    async allotRights() {
      this.dialogRightsVisible = false
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      // console.log(keys)
      const idStr = keys.join(',')
      // console.log(idStr)
      const { data: res } = await this.$http.post('/roles/' + this.roleId + '/rights', { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.getRolesList()
    }
  }
}
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
